package intjavatorpedo.server;

import java.util.HashMap;

import intjavatorpedo.db.BombResult;
import intjavatorpedo.db.Coord;
import intjavatorpedo.db.UserTable;

public class GameStatus {
	private String userName1;
	private String userName2;
	private HashMap<String, UserTable> userTables;
	private HashMap<String, Boolean> userStarted;
	private String userNameOnTurn;
	
	public String getOtherUser(String userName) {
		if (userName.equals(userName1))
			return userName2;
		else if (userName.equals(userName2))
			return userName1;
		else
			return null;
	}
	
	public UserTable getUserTable(String userName) {
		return this.userTables.get(userName);
	}
	
	public boolean otherUserStarted(String userName) {
		String otherUserName = this.getOtherUser(userName);
		if (otherUserName == null)
			return false;
		
		return this.userStarted.get(otherUserName);
	}
	
	public void startGame(String userName) {
		if(!this.userStarted.containsKey(userName))
			return;
		
		this.userStarted.put(userName, true);
	}
	
	public boolean identifyGame(String userName1, String userName2) {
		return this.userName1.equals(userName1) && this.userName2.equals(userName2) ||
				this.userName1.equals(userName2) && this.userName2.equals(userName1);
	}
	
	public BombResult userGuess(String userName, int x, int y) {
		// Return if other user's turn
		if (!userName.equals(userNameOnTurn))
			return BombResult.UNSUCCESSFUL;
		
		String otherUserName = this.getOtherUser(userName);
		if (otherUserName == null)
			return BombResult.UNSUCCESSFUL;
		
		Coord bombed = new Coord(x, y);
		// Bombing other user's table
		BombResult res = this.userTables.get(otherUserName).bomb(bombed);
		bombed.setSuccesfullyBombed(res == BombResult.SUCCESSFUL || res == BombResult.SANK);
		
		// Adding guess
		this.userTables.get(userName).addGuess(bombed);
		
		// Change user on turn
		this.userNameOnTurn = otherUserName;
		
		return res;
	}
	
	public boolean userWon(String userName) {
		String otherUserName = this.getOtherUser(userName);
		if (otherUserName == null)
			return false;
		
		return this.userTables.get(otherUserName).isDead();
	}
	
	public void putRandomShips() {
		this.userTables.get(this.userName1).putRandomShips();
		this.userTables.get(this.userName2).putRandomShips();
	}

	GameStatus(UserTable userTable1, UserTable userTable2) {
		this.userTables = new HashMap<String, UserTable>();
		this.userName1 = userTable1.getUserName();
		this.userName2 = userTable2.getUserName();
		this.userTables.put(userName1, userTable1);
		this.userTables.put(userName2, userTable2);
		this.userNameOnTurn = this.userName1;
		
		this.userStarted = new HashMap<String, Boolean>();
		this.userStarted.put(userName1, false);
		this.userStarted.put(userName2, false);
	}

	public boolean isMyTurn(String userName) {
		return this.userNameOnTurn.equals(userName);
	}
	
	
}
